from starlette.responses import Response, PlainTextResponse, HTMLResponse
from lly.vim.utils import try_except
from fastapi import APIRouter,File,UploadFile
from pathlib import Path
from lly.vim import command
from lly.logconfig import logger
from lly import markdown
from starlette.templating import Jinja2Templates
from starlette.requests import Request
from lly.server import root_path
#  from starlette.staticfiles import StaticFiles
router = APIRouter()
templates = Jinja2Templates(directory=root_path+'templates')

#  router.mount('/static', StaticFiles(directory='src'), name='static')
@router.get('/log')
@try_except
def show_log(request: Request):
    '''
    显示log
    '''

    return templates.TemplateResponse('log.html', {'request': request, 'title': 'log', 'body': command.cmd_history})



@router.get('/{path:path}')
async def visite_file(request: Request, path: str, cmd: str = None):
    '''访问本地文件
    '''
    target_file = Path(path).expanduser().resolve()
    if target_file.is_dir():
        return [str(f) for f in target_file.glob(r'**/*.py')]
    elif target_file.is_file():
        body = vim_url(request, str(target_file), cmd)
        return body
    else:
        logger.exception(target_file)
        return path


@try_except
def vim_url(request: Request, file_path, cmd):
    '''处理vim请求
    '''
    logger.warning(f"{file_path} | { file_path.endswith('.md') } |")
    if file_path.endswith('.dot'):
        cmd_info = command.execute_os_cmd(f'dot {file_path} -Tsvg')
        logger.warning(cmd_info)
        with open(command.cmd_result_path(cmd_info['std_out']), encoding='utf-8') as f:
            body = f.read()
            return templates.TemplateResponse('markdown.html', {"request": request, 'title': Path(file_path).name, 'body': body})
    elif file_path.endswith('.md'):
        if True:
            cmd_info = command.execute_os_cmd(f'pandoc -f markdown {file_path} --toc -t html --mathjax -s -c /static/markdownToc_files/toc.css --metadata title={Path(file_path).name} ')
            logger.warning(cmd_info)
            with open(command.cmd_result_path(cmd_info['std_out']), encoding='utf-8') as f:
                body = f.read()
                return HTMLResponse(body)
        else:
            body = markdown.generet(file_path)
        body = templates.TemplateResponse(
            'markdown_toc.html', {"request": request, 'title': Path(file_path).name, 'body':
                                  body})
        return body
    elif file_path.endswith('.pu') or file_path.endswith('.puml'):
        svg_dir = command.temp_dir
        cmd_info = command.execute_os_cmd(f'{cmd} -o {svg_dir} {file_path}')
        logger.info(cmd_info)
        with open(command.cmd_result_path(Path(file_path).stem, suffix='.svg'), encoding='utf-8') as f:
            body = f.read()
            return templates.TemplateResponse('markdown.html', {"request": request, 'title': Path(file_path).name, 'body': body})
    else:
        with Path(file_path) as file:
            return HTMLResponse(file.read_text())
    return PlainTextResponse(file_path)


def pure_reponse(content):
    return Response(content=content, media_type="application/xml")
